package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {


    @Autowired
    private OrderMapper orderMapper;

    //每五秒执行一次
    /*@Scheduled(cron = "0/5 * * * * ?")
    public void executeTask(){
        log.info("task execute：{}",new Date());
    }*/

    /**
     * 每天凌晨1点执行
     * 用于监测每天未点或忘点完成订单的操作
     */
    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")    //用于测试
    public void executeTask(){
        //查询所有状态为派送的订单
        List<Orders> ordersList = orderMapper.queryByStatusList(Orders.DELIVERY_IN_PROGRESS);
        ordersList.stream().forEach(orders -> {
            LocalDateTime time = orders.getOrderTime();
            LocalDateTime now = LocalDateTime.now();
            //如果订单时间超过1小时，自动完成订单
            if (now.minusHours(1).isBefore(time)){
                return;
            }
            orders.setStatus(Orders.COMPLETED);
            orderMapper.update(orders);
        });
        log.info("修改派送中订单状态为已完成");
    }

    /**
     * 每隔五分钟执行一次
     * 用于监测下单后未支付的订单
     */
    @Scheduled(cron = "0 0/5 * * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")  //用于测试
    public void executeTask2(){
        //查询所有状态为未支付的订单
        List<Orders> ordersList = orderMapper.queryByStatusList(Orders.PAID);
        ordersList.stream().forEach(orders -> {
            LocalDateTime time = orders.getOrderTime();
            LocalDateTime now = LocalDateTime.now();
            //如果订单时间超过30分钟，自动取消订单
            if (now.minusMinutes(15).isBefore(time)){
                return;
            }
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason("超时未支付");
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.update(orders);
        });
        log.info("修改未支付订单状态为已取消");
    }
}
